package com.yu.myiptv;

import static android.view.Menu.NONE;
import static android.view.View.FOCUS_DOWN;
import static android.view.ViewGroup.FOCUS_AFTER_DESCENDANTS;

import static java.lang.Math.max;

import android.annotation.SuppressLint;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.GravityCompat;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.audio.AudioAttributes;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.material.internal.NavigationMenuItemView;
import com.google.android.material.navigation.NavigationView;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class MainActivity extends AppCompatActivity {
    private PlayerView playerView;
    private ExoPlayer player;
    private String channel_uri;
    private List<Channel> channelList;
    private int channel_idx = 0;
    private int focus_idx = 0;
    private GestureDetector gesture;
    private int channel_idx_max = 0;

    private NavigationView navigationView;
    private RecyclerView navRecyclerView;
    private DrawerLayout drawerLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.player_view), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        var intent = getIntent();
        channel_uri = intent.getStringExtra("url");

        //侧滑菜单
        navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(item -> {
            channel_idx = item.getItemId();
            focus_idx = channel_idx;
            item.setChecked(true);
            //
            setFocus();
            channelChanged();
            return true;
        });
        navigationView.setAnimation(null);
        drawerLayout = findViewById(R.id.drawer_layout);
        //comp();
        initializeSlider();
        //查找RecyclerView
        for (int i = 0; i < navigationView.getChildCount(); i++) {
            View child = navigationView.getChildAt(i);
            if (child instanceof RecyclerView) {
                navRecyclerView = (RecyclerView) child;
                break;
            }
        }

        //navigationView
        drawerLayout.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
            @Override
            public void onDrawerOpened(@NonNull View drawerView) {
                super.onDrawerOpened(drawerView);
                Menu menu = navigationView.getMenu();
                var item = menu.getItem(channel_idx);
                if (item != null && !item.isChecked()) {
                    item.setChecked(true);
                }

                setFocus();
            }
        });

        //初始化播放器
        playerView = findViewById(R.id.player_view);
        playerView.setFocusable(false);
        try {
            initializeMediaPlayer();
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
        //屏幕方向
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);

    }

    private void initializeMediaPlayer() throws NoSuchFieldException {
        player = new ExoPlayer.Builder(this, new FfmpegRenderersFactory(this)).build();
        player.setAudioAttributes(AudioAttributes.DEFAULT, /* handleAudioFocus= */ true);
        playerView.setPlayer(player);
        playerView.setUseController(false);

        //手势
        gesture = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onDown(@NonNull MotionEvent e) {
                return true;
            }

            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                try {
                    // 检查上滑或下滑
                    if (Math.abs(e1.getY() - e2.getY()) > 30 && Math.abs(velocityY) > 30) {
                        if (e1.getY() - e2.getY() > 0) {
                            // 上滑
                            changeChannel(1);
                        } else {
                            // 下滑
                            changeChannel(-1);
                        }
                        channelChanged();
                        return true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return false;
            }

            @Override
            public boolean onSingleTapUp(@NonNull MotionEvent e) {
                if (drawerLayout.isOpen()) {
                    drawerLayout.close();
                } else {
                    drawerLayout.open();
                }
                return true;
            }
        });

        String url = "http://ucdn.sd.chinamobile.com:8089/00/SNM/CHANNEL00000311/index.m3u8";
        if (channel_uri == null)
            channel_uri = url;
        MediaItem mediaItem = MediaItem.fromUri(Uri.parse(channel_uri));
        player.setMediaItem(mediaItem);
        player.prepare();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return gesture.onTouchEvent(event);
    }

    @Override
    protected void onResume() {
        playerView.setOnTouchListener((v, event) -> gesture.onTouchEvent(event));

        if (player != null) {
            player.play();
        }
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (player != null) {
            player.pause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (player != null) {
            player.release();
            player = null;
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            int keyCode = event.getKeyCode();
            switch (keyCode) {
                case KeyEvent.KEYCODE_MENU:
                    //menu open
                    if (!drawerLayout.isOpen()) {
                        drawerLayout.open();
                    } else {
                        drawerLayout.close();
                    }
                    return true;
                case KeyEvent.KEYCODE_DPAD_UP:
                    if (!drawerLayout.isOpen()) {
                        boolean changed = changeChannel(-1);
                        if (changed) {
                            channelChanged();
                            return true;
                        }
                    }
                    break;
                case KeyEvent.KEYCODE_DPAD_DOWN:
                    if (!drawerLayout.isDrawerVisible(GravityCompat.START)) {
                        boolean changed = changeChannel(1);
                        if (changed) {
                            channelChanged();
                            return true;
                        }
                    }
                    break;
                case KeyEvent.KEYCODE_BACK:
                    if (drawerLayout.isOpen()) {
                        drawerLayout.close();
                        return true;
                    }
            }
        }
        return super.dispatchKeyEvent(event);
    }

    private void initializeSlider() {
        //read channels
        channelList = FileUtils.loadChannelsFromFile(getBaseContext());
        channel_idx_max = channelList.size() - 1;
        //修改菜单项
        Menu menu = navigationView.getMenu();
        for (var ch : channelList) {
            menu.add(NONE, ch.getChannelId(), ch.getChannelId(), ch.getName())
                    .setCheckable(true);

        }
        setupFocusOrder(menu);
    }

    private boolean changeChannel(int step) {
        boolean changed = true;
        channel_idx += step;
        if (channel_idx < 0) {
            channel_idx = 0;
            changed = false;
        }
        if (channel_idx > channel_idx_max) {
            channel_idx = channel_idx_max;
            changed = false;
        }
        return changed;

    }

    private void channelChanged() {
        Toast.makeText(this, channelList.get(channel_idx).getName(), Toast.LENGTH_SHORT).show();
        var url_template = "http://ucdn.sd.chinamobile.com:8089/00/SNM/%s/index.m3u8";
        var url = String.format(url_template, channelList.get(channel_idx).getUrl());
        MediaItem mediaItem = MediaItem.fromUri(Uri.parse(url));
        player.stop();
        player.setMediaItem(mediaItem);
        player.prepare();
        player.play();
    }

    private int getCurrentIndex() {
        MenuItem checked = navigationView.getCheckedItem();
        if (checked == null) return -1;

        for (int i = 0; i < navigationView.getMenu().size(); i++) {
            if (navigationView.getMenu().getItem(i).getItemId() == checked.getItemId()) {
                return i;
            }
        }
        return -1;
    }

    private void setupFocusOrder(Menu menu) {
        for (int i = 0; i < menu.size(); i++) {
            MenuItem item = menu.getItem(i);
            View view = navigationView.findViewById(item.getItemId());
            if (view != null) {
                if (i > 0) {
                    View prevView = navigationView.findViewById(menu.getItem(i - 1).getItemId());
                    view.setNextFocusUpId(prevView.getId());
                }
                if (i < menu.size() - 1) {
                    View nextView = navigationView.findViewById(menu.getItem(i + 1).getItemId());
                    view.setNextFocusDownId(nextView.getId());
                }
            }
        }
    }

    private void setFocusToNextItem(int selectedPosition) {
        var menu = navigationView.getMenu();
        var nextPosition = selectedPosition + 1;
        if (nextPosition > channel_idx_max) nextPosition = channel_idx_max;

        var item = menu.getItem(nextPosition);
        var itemView = navigationView.findViewById(item.getItemId());
        if (itemView != null) {
            Log.d("focus", itemView.toString());
            itemView.setFocusable(true);
            boolean r = itemView.requestFocus();
            if (r) {
                Log.d("focus", "success: " + nextPosition);
            } else {
                Log.d("focus", "failed: " + nextPosition);
            }
        }
    }

    private void setFocus() {
        // 添加布局监听器，确保菜单项已渲染
        navigationView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @SuppressLint("RestrictedApi")
            @Override
            public void onGlobalLayout() {
                // 移除监听，避免重复调用
                navigationView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                int targetItemId = Objects.requireNonNull(navigationView.getCheckedItem()).getItemId();
                // 遍历 NavigationView 的子视图
                for (int j = 0; j < navRecyclerView.getChildCount(); j++) {
                    View menuItemView = navRecyclerView.getChildAt(j);
                    if (menuItemView instanceof NavigationMenuItemView) {
                        var itemView = (NavigationMenuItemView) menuItemView;
                        MenuItem item = itemView.getItemData();
                        if (item.getItemId() == targetItemId) {
                            // 找到目标视图，请求焦点
                            Log.d("focus", "setFocus," + item.getTitle());
                            itemView.requestFocus();
                            // 可选：滚动到该项（确保可见）
                            //navRecyclerView.smoothScrollToPosition(j);
                            return;
                        }
                    }
                }
            }
        });
    }

//end
}